package com.southwind.springboottest.study.Java读写锁;

import java.util.HashMap;

/**
 * @description：TODO 测试添加读写锁控制并发的map用法
 * @author： HXG
 * @create： 2023/12/15 15:16
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        final ReadWriteMap<String, String> map = new ReadWriteMap<>(new
                HashMap<>());
        map.put("one", "init value");
        for (int i = 1; i <= 4; i++) {
            new WorkThread(map).start();
        }
    }
    // 模拟工作的线程
    static class WorkThread extends Thread {
        private ReadWriteMap<String, String> map;
        public WorkThread(ReadWriteMap<String, String> map) {
            this.map = map;
        }
        @Override
        public void run() {
            for (int i = 1; i <= 2; i++) {
                try {
                    System.out.println(this.toString() + " read out: " +
                            map.get("one"));

                    map.put("one", this.toString() +
                            System.currentTimeMillis());

                    Thread.sleep(2);

                    System.out.println(this.toString() + " read out: " +
                            map.get("one"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
